package com.jf.cloud.im.service.impl;

import com.jf.cloud.common.database.dto.PageDTO;
import com.jf.cloud.common.database.util.PageUtil;
import com.jf.cloud.common.database.vo.PageVO;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.im.dto.ImMsgBizSkillsDTO;
import com.jf.cloud.im.mapper.ImMsgBizSkillsMapper;
import com.jf.cloud.im.service.ImMsgBizSkillsService;
import com.jf.cloud.im.vo.ImMsgBizSkillsVO;
import org.springframework.stereotype.Service;

import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 客服自动回复表
 *
 * @author zz
 * @date 2023-03-23 17:43:40
 */
@Service
public class ImMsgBizSkillsServiceImpl implements ImMsgBizSkillsService {

    @Autowired
    private ImMsgBizSkillsMapper imMsgBizSkillsMapper;

    @Override
    public PageVO<ImMsgBizSkillsVO> page(PageDTO pageDTO, ImMsgBizSkillsDTO imMsgBizSkillsDTO, Long shopId) {
        return PageUtil.doPage(pageDTO, () -> imMsgBizSkillsMapper.list(imMsgBizSkillsDTO, shopId));
    }

    @Override
    public ImMsgBizSkillsVO getById(Long id) {
        return imMsgBizSkillsMapper.getById(id);
    }

    @Override
    public void save(ImMsgBizSkillsVO imMsgBizSkills) {
        checkSkills(imMsgBizSkills);
        imMsgBizSkills.setStatus(1);
        imMsgBizSkills.setCreateTime(new Date());
        imMsgBizSkills.setUpdateTime(new Date());
        imMsgBizSkillsMapper.save(imMsgBizSkills);
    }

    @Override
    public void update(ImMsgBizSkillsVO imMsgBizSkills) {
        checkSkills(imMsgBizSkills);
        imMsgBizSkills.setUpdateTime(new Date());
        imMsgBizSkillsMapper.update(imMsgBizSkills);
    }

    @Override
    public void deleteById(Long id) {
        imMsgBizSkillsMapper.deleteById(id);
    }

    @Override
    public List<ImMsgBizSkillsVO> getByShopId(Long shopId){
        return imMsgBizSkillsMapper.getByShopId(shopId);
    }

    private void checkSkills(ImMsgBizSkillsVO imMsgBizSkills){
        ImMsgBizSkillsVO selectOne = imMsgBizSkillsMapper.selectByShopIdAndKey(imMsgBizSkills.getShopId(), imMsgBizSkills.getKeywords());
        if(Objects.nonNull(selectOne)){
            if(imMsgBizSkills.getId() != null && Objects.equals(imMsgBizSkills.getId(), selectOne.getId())){
                return;
            }else{
                throw new LuckException("关键字重复");
            }
        }
    }
}